import ProPage from '@/components/ProPage';
import {
  BorderOuterOutlined,
  CloseOutlined,
  ColumnWidthOutlined,
  DeleteOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { Dropdown, Menu, message, Tabs } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { history, useIntl, useLocation } from 'umi';
import routes from '../../../config/routes';

const { TabPane } = Tabs;
const STORAGE_KEY = 'multi_tabs'; // sessionStorage 记录 key
const MAX_TABS = 20; // 最大标签页数量
const TAB_HEIGHT = 40; // 标签页高度

// 类型定义
interface TabItem {
  key: string;
  title: string;
  icon?: string;
  closable?: boolean;
  refresh?: boolean;
}

interface RouteItem {
  path: string;
  name: string;
  routes?: RouteItem[];
  icon?: string;
}

// 样式组件
const StyledTabs = styled(Tabs)`
  .ant-tabs-nav {
    height: ${TAB_HEIGHT}px;
    margin: 0;
    padding: 6px 6px 0;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    background: #fff;
    border-radius: 4px;
    scrollbar-width: thin;
    scrollbar-color: #d9d9d9 #f5f5f5;

    &::-webkit-scrollbar {
      height: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f5f5f5;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #d9d9d9;
      border-radius: 3px;

      &:hover {
        background: #bfbfbf;
      }
    }
  }

  .ant-tabs-nav-wrap {
    padding-bottom: 0;
  }

  .ant-tabs-tab {
    display: inline-flex;
    align-items: center;
    height: ${TAB_HEIGHT - 6}px;
    margin: 0 4px 0 0;
    padding: 8px 16px;
    background: #fafafa;
    border: 1px solid #f0f0f0;
    border-radius: 4px 4px 0 0;
    transition: all 0.3s;

    &:hover {
      background: #f5f5f5;
    }

    &.ant-tabs-tab-active {
      background: #fff;
      border-bottom-color: #fff;
    }
  }

  .ant-tabs-tab-btn {
    display: flex;
    gap: 4px;
    align-items: center;
  }

  .ant-tabs-ink-bar {
    display: none;
  }
`;

/**
 * 递归查找路由
 * @param routes 路由
 * @param path 路由路径
 */
const getBreadcrumb = (path: string, routes: RouteItem[]) => {
  let breadcrumb: string[] = [];

  const findRoute = (list: RouteItem[], parentNames: string[] = []): RouteItem | undefined => {
    for (const route of list) {
      const newParentNames = [...parentNames, route.name];
      if (route.path === path) {
        breadcrumb = newParentNames;
        return route;
      }
      if (route.routes) {
        const currentRoute = findRoute(route.routes, newParentNames);
        if (currentRoute) {
          return currentRoute;
        }
      }
    }
    return undefined;
  };

  const currentRoute = findRoute(routes);
  return {
    name: breadcrumb.join('.'),
    route: currentRoute,
  };
};

const MultiTabs: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const location = useLocation();
  const [tabs, setTabs] = useState<TabItem[]>([]);
  const [targetTabKey, setTargetTabKey] = useState<string | null>(null);
  const [refreshKey, setRefreshKey] = useState<string>('');
  const intl = useIntl();

  // 读取 sessionStorage 里的 tabs
  useEffect(() => {
    const storedTabs = sessionStorage.getItem(STORAGE_KEY);
    if (storedTabs) {
      try {
        const parsedTabs = JSON.parse(storedTabs);
        if (Array.isArray(parsedTabs) && parsedTabs.length > 0) {
          setTabs(parsedTabs);
          // 如果当前路径不在标签页中，添加当前路径的标签页
          if (!parsedTabs.some(tab => tab.key === location.pathname)) {
            addTab(location.pathname);
          }
        } else {
          initTabs();
        }
      } catch (e) {
        initTabs();
      }
    } else {
      initTabs();
    }
  }, []);

  // 初始化标签页
  const initTabs = useCallback(() => {
    const homeTab = { key: '/', title: '首页', closable: false };
    setTabs([homeTab]);
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify([homeTab]));
  }, []);

  // 添加标签页
  const addTab = useCallback((path: string) => {
    const { route, name } = getBreadcrumb(path, routes as any);
    if (!route) return;

    const routeName = intl.formatMessage({
      id: `menu.${name}`,
      defaultMessage: name,
    });

    setTabs(prevTabs => {
      if (prevTabs.some(tab => tab.key === path)) {
        return prevTabs;
      }

      if (prevTabs.length >= MAX_TABS) {
        message.warning(`最多只能打开 ${MAX_TABS} 个标签页`);
        return prevTabs;
      }

      const newTabs = [...prevTabs, {
        key: path,
        title: routeName,
        icon: route.icon,
        closable: path !== '/',
      }];

      sessionStorage.setItem(STORAGE_KEY, JSON.stringify(newTabs));
      return newTabs;
    });
  }, [intl]);

  // 监听路由变化，新增或切换标签页
  useEffect(() => {
    if (location.pathname) {
      addTab(location.pathname);
    }
  }, [location.pathname, addTab]);

  // 保存 tabs 到 sessionStorage
  const saveTabs = useCallback((newTabs: TabItem[]) => {
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(newTabs));
    setTabs(newTabs);
  }, []);

  // 关闭标签页
  const removeTab = useCallback(
    (targetKey: string) => {
      setTabs(prevTabs => {
        const newTabs = prevTabs.filter((tab) => tab.key !== targetKey);
        saveTabs(newTabs);

        if (targetKey === location.pathname) {
          const lastTab = newTabs[newTabs.length - 1];
          history.push(lastTab?.key || '/');
        }
        return newTabs;
      });
    },
    [location.pathname, saveTabs],
  );

  // 刷新当前标签页
  const refreshTab = useCallback(() => {
    setRefreshKey(Date.now().toString());
  }, []);

  // 关闭所有标签页
  const closeAllTabs = useCallback(() => {
    const homeTab = tabs.find(tab => tab.key === '/');
    const newTabs = homeTab ? [homeTab] : [];
    saveTabs(newTabs);
    history.push('/');
  }, [tabs, saveTabs]);

  // 关闭其他标签页
  const closeOtherTabs = useCallback(() => {
    if (!targetTabKey) return;
    const homeTab = tabs.find(tab => tab.key === '/');
    const currentTab = tabs.find(tab => tab.key === targetTabKey);
    const newTabs = [homeTab, currentTab].filter(Boolean) as TabItem[];
    saveTabs(newTabs);
  }, [tabs, targetTabKey, saveTabs]);

  // 关闭右侧标签页
  const closeRightTabs = useCallback(() => {
    if (!targetTabKey) return;
    const targetIndex = tabs.findIndex((tab) => tab.key === targetTabKey);
    const newTabs = tabs.slice(0, targetIndex + 1);
    saveTabs(newTabs);
  }, [tabs, targetTabKey, saveTabs]);

  // 右键菜单
  const menu = useMemo(
    () => (
      <Menu>
        <Menu.Item
          icon={<CloseOutlined />}
          disabled={tabs.length === 1 || targetTabKey !== location.pathname}
          key="closeCurrent"
          onClick={() => removeTab(targetTabKey!)}
        >
          关闭当前
        </Menu.Item>
        <Menu.Item icon={<ReloadOutlined />} key="refresh" onClick={refreshTab}>
          刷新页面
        </Menu.Item>
        <Menu.Item
          icon={<DeleteOutlined />}
          disabled={tabs.length === 1}
          key="closeAll"
          onClick={closeAllTabs}
        >
          关闭所有
        </Menu.Item>
        <Menu.Item
          icon={<BorderOuterOutlined />}
          disabled={tabs.length === 1}
          key="closeOther"
          onClick={closeOtherTabs}
        >
          关闭其他
        </Menu.Item>
        <Menu.Item
          icon={<ColumnWidthOutlined />}
          disabled={tabs.length === 1}
          key="closeRight"
          onClick={closeRightTabs}
        >
          关闭右侧
        </Menu.Item>
      </Menu>
    ),
    [
      tabs,
      targetTabKey,
      location.pathname,
      removeTab,
      refreshTab,
      closeAllTabs,
      closeOtherTabs,
      closeRightTabs,
    ],
  );

  return (
    <ProPage>
      <ProCard
        bordered
        size="small"
        ghost
        bodyStyle={{ padding: 0 }}
      >
        <StyledTabs
          type="editable-card"
          hideAdd
          size="small"
          activeKey={location.pathname}
          onChange={(key) => history.push(key)}
          onEdit={(targetKey, action) => action === 'remove' && removeTab(targetKey as string)}
        >
          {tabs.map((tab) => (
            <TabPane
              tab={
                <Dropdown overlay={menu} trigger={['contextMenu']}>
                  <div onContextMenu={() => setTargetTabKey(tab.key)}>
                    {tab.icon && <span className={`anticon ${tab.icon}`} />}
                    {tab.title}
                  </div>
                </Dropdown>
              }
              key={tab.key}
              closable={tab.closable}
            >
              <ProCard ghost bodyStyle={{ padding: 0, marginTop: 8 }}>
                {location.pathname === tab.key ? children : null}
              </ProCard>
            </TabPane>
          ))}
        </StyledTabs>
      </ProCard>
    </ProPage>
  );
};

export default MultiTabs;
